package cn.nawang.ebeim.ui.server;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;

public class RestServer implements ApplicationContextAware{

  private Server server;  
  private ApplicationContext applicationContext;  

  public void setApplicationContext(ApplicationContext applicationContext)  
          throws BeansException {  
      this.applicationContext = applicationContext;  
        
  }  
  
  public void start() throws Exception {
    server = new Server(8080);
    WebAppContext webAppContext = new WebAppContext();  
    
    webAppContext.setContextPath("/");  
    webAppContext.setDescriptor("webapp/WEB-INF/web.xml");  
    webAppContext.setResourceBase("webapp");  
    webAppContext.setConfigurationDiscovered(true);  
    webAppContext.setParentLoaderPriority(true);  
    server.setHandler(webAppContext);  
      
    webAppContext.setClassLoader(applicationContext.getClassLoader());  
      
    XmlWebApplicationContext xmlWebAppContext = new XmlWebApplicationContext();  
    xmlWebAppContext.setParent(applicationContext);  
    xmlWebAppContext.setConfigLocation("");  
    xmlWebAppContext.setServletContext(webAppContext.getServletContext());  
    xmlWebAppContext.refresh();  
      
    webAppContext.setAttribute(  
            WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,  
            xmlWebAppContext);  

    server.start();
    //server.join();
  }
  public static void main(String[] args) throws Exception {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("ui-servlet.xml");     
    applicationContext.registerShutdownHook();     
  }

}
